--[[
<extension name="testLua6">
       <condition field="destination_number" expression="^7(\d+)$">
          <action application="lua" data="testGateway.lua"/>
          <action application="limit" data="${useBackend} ${useRealm} ${id} ${lines} user_busy XML default"/>
          <action application="bridge" data="{origination_caller_id_number=$1,origination_caller_id_name=$1}sofia/internal/$1@${callContact}"/>
       </condition>
</extension>
]]


--先将gateway信息写死
--local
gatewayList = { [1] = { ["gatewayName"] = "mx8", ["lines"] = "1", ["user"] = "19900000000", ["url"] = "172.16.8.88", [
"contact"] = nil }, [2] = { ["gatewayName"] = "ds", ["lines"] = "3", ["user"] = "19900000001", [
"url"] = "172.16.8.88" }, ["contact"] = nil }
--local
gatewayList = { [1] = { ["gatewayName"] = "dx16_1903", ["lines"] = "16", ["user"] = "19900000003", [
"url"] = "172.16.200.60", ["contact"] = nil }, [2] = { ["gatewayName"] = "swx32_200_81", ["lines"] = "32", [
"user"] = "19900000004", ["url"] = "172.16.200.60", ["contact"] = nil } }
local
gatewayList = { [1] = { ["gatewayName"] = "swx32_200_81", ["lines"] = "32", ["user"] = "19900000004", [
"url"] = "172.16.200.60", ["contact"] = nil } }
local
count = 0;
--获取数组长度

for k, v in pairs(gatewayList) do
    count = count + 1
end

session:setAutoHangup(false) --设置不要自动挂机, 否则当此脚本执行完, 会自动挂机

local
selectGateway = nil -- 最终将会选用的网关

local
api = freeswitch.API();
--freeswitch的API

while (count > 0 and session
        :ready() == true)    --随机选择一个gateway, 假如选到的gateway为空闲的, 就停止循环, 否则继续(要注意判断session的状态, 否则可能有死循环)
do

    local
    index = math.random(1, count) - -随机索引

    local
    gateway = gatewayList[index] - -选择list中的gateway

    local
    gatewayName = gateway["gatewayName"];
    --获取gatewayName

    local
    gatewayUser = gateway["user"];
    --获取此网关注册到freeswitch的用户名

    local
    gatewayStatus = api:executeString("sofia status profile internal user " .. gatewayUser ..
            "@" .. gateway["url"]); --查询当前gateway是否在线

    beginIndex, _ = string.find(gatewayStatus, "User");
    --截取字符串

    if (beginIndex ~= nil) --假如不为nil, 就是gateway已经在线
    then
        local
        result = api:execute("limit_usage", "hash gatewayList " .. gatewayName);
        --查询gateway已用线路

        freeswitch.consoleLog("INFO", "当前网关为" .. gatewayName ..
                "使用已用线路:" .. result ..
                ",总可用为" .. gateway["lines"]) --打印gateway线路日志

        if (result ~= gateway["lines"]) --假如已用线路等于最大线路, 就再继续随机选一个, 假如不是, 就选用这个gateway
        then
            --获取注册contact头
            _, contactBeginIndex = string.find(gatewayStatus, "sip:" .. gatewayUser ..
                    "@");
            contactEndIndex, _ = string.find(gatewayStatus, ">");
            local
            contact = string.sub(gatewayStatus, contactBeginIndex + 1, contactEndIndex - 1);
            gateway["contact"] = contact
            selectGateway = gateway - -赋值给最终选择的gateway
            break
        else
            freeswitch.consoleLog("INFO", "当前网关为" .. gatewayName ..
                    "线路已满,重新选择") --打印gateway线路日志
        end
    else
        freeswitch.consoleLog("INFO", "网关" .. gatewayName ..
                "尚未注册") --打印gateway线路日志
    end

    table.remove(gatewayList, index);
    --从list中踢出, 下次就不会选到了

    count = count - 1;
    --list总长度减1

end

if (selectGateway ~= nil) --假如selectGateway(最终选用网关)不为空, 就用它呼出, 假如为空, 就表示全部gateway都忙线
then
    session:setVariable("gateway", selectGateway["gatewayName"]) --设置app
    --limit参数
    session:setVariable("useBackend", "hash") --设置app
    --limit的backend参数
    session:setVariable("useRealm", "gatewayList") --设置app
    --limit的realm参数
    session:setVariable("lines", selectGateway["lines"]) --设置app
    --limit的max参数
    session:setVariable("id", selectGateway["gatewayName"]) --设置app
    --limit的resource参数
    session:setVariable("callContact", selectGateway["contact"]) --设置外呼字符串的参数
    freeswitch.consoleLog("INFO", "最终选择外呼的网关为" .. selectGateway["gatewayName"]) --打印gateway线路日志
    --[[ACTIONS = {--本来这里可以直接执行action的, 但是不知道为啥不生效
                   {"log", "测试测试"},
                   {"limit", "hash gatewayList "..selectGateway["gatewayName"].." "..selectGateway["lines"]..
                    " user_busy XML default"},
                   {"bridge", "sofia/gateway/"..selectGateway["gatewayName"].."/"..session:getVariable("calleeNumber")}
    }]]

else
    custom_msg = "sessionId: " .. session:get_uuid();
    local
    e = freeswitch.Event("custom", "dial::lineBusy");
    e:addHeader("sessionId", session:get_uuid());
    e:addBody(custom_msg);
    e:fire();
    freeswitch.consoleLog("INFO", "当前没有任何的空闲线路了") --打印gateway线路日志
    session:streamFile("/usr/local/freeswitch/sounds/user/lineBusy.wav", "3") --假如没有线路, 播放忙音语音
end

